package org.example;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson2.JSON;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main ( String[] args ) throws Exception
    {
        String month = "";
        Set<String> nameSet = new HashSet<>();

        HashMap<String,Set<String>> swapNameMap = new HashMap<>();
        initSwapNameMap(swapNameMap);

        String path = "D:\\ddd\\123\\";
        File file = new File(path);
        File[] files = file.listFiles();
        Map<String,List<Map<String,Object>>> fileMap = new HashMap<>();
        for (File temp : files) {
            String fileName = temp.getName();
            if(fileName.startsWith("aiting") || fileName.startsWith("mv") || fileName.startsWith("single") || fileName.startsWith("song")){
                if(fileName.startsWith("song")){
                    month = fileName.split("_")[6].substring(0,6);
                }
                ExcelReader reader = ExcelUtil.getReader(temp);
                List<Map<String,Object>> dataAll = reader.readAll();
                fileMap.put(fileName,dataAll);
                for (int i = 0; i < dataAll.size(); i++) {
                    Map<String, Object> objectMap = dataAll.get(i);
                    String name = objectMap.get("歌手名").toString();
                    nameSet.add(name);
                }
            }
        }
        excuteNameSet(nameSet,swapNameMap);
        for (String name : nameSet) {
            Set<String> swapNameSet = swapNameMap.get(name);
            if(swapNameSet==null){
                swapNameSet = new HashSet<>();
            }
            File nameFile = new File(path+"file/" + name + month + "结算明细.xlsx");
            BigDecimal qq = BigDecimal.ZERO;
            BigDecimal kw = BigDecimal.ZERO;
            BigDecimal kg = BigDecimal.ZERO;
            BigDecimal at = BigDecimal.ZERO;
            ExcelWriter writer = ExcelUtil.getWriter(nameFile);
            //writer.autoSizeColumnAll();
            for (Map.Entry<String,List<Map<String,Object>>> entry : fileMap.entrySet()){
                String fileName = entry.getKey();
                List<Map<String,Object>> data = entry.getValue();
                Set<String> finalSwapNameSet = swapNameSet;
                List<Map<String, Object>> data2Excel = data.stream().filter(a -> {
                    String userName = a.get("歌手名").toString();
                    return (name.equals(userName) || finalSwapNameSet.contains(userName));
                }).collect(Collectors.toList());
                if(!data2Excel.isEmpty()){
                    BigDecimal total = BigDecimal.ZERO;
                    for(Map<String,Object> a : data){
                        String userName = a.get("歌手名").toString();
                        if(name.equals(userName) || finalSwapNameSet.contains(userName)){
                            total = total.add(new BigDecimal(a.get("CP分成收入").toString()));
                        }
                    }
                    /*int total =  data.stream().mapToInt(a->{
                        String userName = a.get("歌手名").toString();
                        if(name.equals(userName) || finalSwapNameSet.contains(userName)){
                            return (int)Math.round(Double.parseDouble(a.get("CP分成收入").toString())*100.00);
                        }
                        return 0;
                    }).sum();*/
                    if(fileName.startsWith("aiting")){
                        at = at.add(total);
                    }
                    if(fileName.indexOf("kw")>0){
                        kw = kw.add(total);
                    }
                    if(fileName.indexOf("kg")>0){
                        kg = kg.add(total);
                    }
                    if(fileName.indexOf("qq")>0){
                        qq = qq.add(total);
                    }
                    HashMap<String,Object> totalItem = new HashMap<>();
                    totalItem.put("CP分成收入",total.setScale(3, BigDecimal.ROUND_HALF_UP));
                    data2Excel.add(totalItem);
                    executeSheet(writer,fileName);
                    writer.write(data2Excel,true);
                }
            }
            executeSum(writer,kw,kg,qq,at,month);
            StyleSet style = writer.getStyleSet();
            Font font = writer.createFont();
            font.setColor(IndexedColors.BLACK.getIndex());
            font.setBold(true);
            font.setFontHeightInPoints((short) 16);
            //重点，设置中文字体
            font.setFontName("宋体");
            CellStyle headCellStyle = style.getHeadCellStyle();
            headCellStyle.setFont(font);

            int sheetCount = writer.getSheetCount();
            for(int k=0;k<sheetCount;k++){
                writer.setSheet(k);
                writer.setRowHeight(0,k==0?30:45);
                writer.autoSizeColumnAll();
            }
            writer.close();
        }
    }

    public static void executeSum(ExcelWriter writer,BigDecimal kw,BigDecimal kg,BigDecimal qq,BigDecimal at,String month){
        BigDecimal total = kw.add(kg).add(qq).add(at);
        //结算平台	结算区间	分成合计
        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("结算平台", "QQ音乐");
        row1.put("结算区间", month);
        row1.put("分成合计(RMB元)", qq.setScale(3, BigDecimal.ROUND_HALF_UP));
        Map<String, Object> row2 = new LinkedHashMap<>();
        row2.put("结算平台", "酷狗");
        row2.put("结算区间", month);
        row2.put("分成合计(RMB元)", kg.setScale(3, BigDecimal.ROUND_HALF_UP));
        Map<String, Object> row3 = new LinkedHashMap<>();
        row3.put("结算平台", "酷我");
        row3.put("结算区间", month);
        row3.put("分成合计(RMB元)", kw.setScale(3, BigDecimal.ROUND_HALF_UP));
        Map<String, Object> row4 = new LinkedHashMap<>();
        row4.put("结算平台", "爱听音乐");
        row4.put("结算区间", month);
        row4.put("分成合计(RMB元)", at.setScale(3, BigDecimal.ROUND_HALF_UP));
        Map<String, Object> row5 = new LinkedHashMap<>();
        row5.put("分成合计(RMB元)", total.setScale(3, BigDecimal.ROUND_HALF_UP));
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2,row3, row4,row5);
        writer.setSheet(0);
        writer.renameSheet(0,"汇总");
        writer.write(rows);

    }

    public static void executeSheet(ExcelWriter writer,String fileName){
        if(fileName.startsWith("aiting")){
            writer.setSheet("爱听明细表");
        }if(fileName.startsWith("mv")){
            if(fileName.indexOf("qq")>0){
                writer.setSheet("QQ音乐MV明细表");
            }
            if(fileName.indexOf("kg")>0){
                writer.setSheet("酷狗音乐MV明细表");
            }
        }if(fileName.startsWith("single")){
            if(fileName.indexOf("kw")>0){
                writer.setSheet("酷我音乐单曲订购明细表");
            }
            if(fileName.indexOf("kg")>0){
                writer.setSheet("酷狗音乐单曲订购明细表");
            }
            if(fileName.indexOf("qq")>0){
                writer.setSheet("QQ音乐单曲订购明细表");
            }
        }if(fileName.startsWith("song")){
            if(fileName.indexOf("kw")>0){
                writer.setSheet("酷我音乐明细表");
            }
            if(fileName.indexOf("kg")>0){
                writer.setSheet("酷狗音乐明细表");
            }
            if(fileName.indexOf("qq")>0){
                writer.setSheet("QQ音乐明细表");
            }
        }
    }

    public static void excuteNameSet(Set<String> nameSet,HashMap<String,Set<String>> swapNameMap){
        swapNameMap.values().forEach(a->{
            nameSet.removeAll(a);
        });
        Set<String> removedNames = new HashSet<>();
        ArrayList<String> nameList = new ArrayList<>(nameSet);
        Collections.sort(nameList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        for (int i = 0; i < nameList.size(); i++) {
            String name = nameList.get(i);
            nameSet.forEach(a->{
                if(name.length()>a.length() && name.indexOf(a)>=0){
                    removedNames.add(name);
                    Set<String> names = swapNameMap.get(a);
                    if(names==null){
                        names = new HashSet<>();
                    }
                    names.add(name);
                    swapNameMap.put(a,names);
                }
            });
        }
        nameSet.removeAll(removedNames);
    }

    public static void initSwapNameMap(HashMap<String,Set<String>> swapNameMap){
        Set<String> nameSet = new HashSet<>();
        nameSet.add("The Verse");
        swapNameMap.put("陈绮贞",nameSet);
    }
}
